package com.acane.instagram.feature.home

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.media3.exoplayer.ExoPlayer
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.dto.CommentDTO
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.core.model.response.NetworkResponse
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

@SuppressLint("MutableCollectionMutableState")
class HomeViewModel: ViewModel() {
    private val _postDatum = MutableStateFlow<List<PostInfo>>(emptyList())
    private val _userDatum = MutableStateFlow<List<UserInfo>>(emptyList())
    val postDatum: MutableStateFlow<List<PostInfo>> = _postDatum
    val userDatum: MutableStateFlow<List<UserInfo>> = _userDatum
    var loginResponse by mutableStateOf<NetworkResponse<UserInfo>?> (null)

    private val _isFollowing = MutableStateFlow<Boolean> (false)
    val isFollowing: StateFlow<Boolean> get() = _isFollowing.asStateFlow()
    fun updateIsFollowing(isFollowing : Boolean) {
        _isFollowing.value = isFollowing
    }


    private var _refresh = MutableStateFlow<Boolean>(false)
    val refresh = _refresh
    fun startRefresh() {
        viewModelScope.launch {
            _refresh.value = true
            delay(1000)
            _refresh.value = false
            // 刷新首页帖子数据
            loadRecommendations()
            postId.value?.let { loadComments(it) }
        }
    }



    private val _postId = MutableStateFlow<String?>(null)
    val postId: StateFlow<String?> get() = _postId.asStateFlow()

    fun updatePostId(newPostId: String?) {
        _postId.value = newPostId
    }

    var caption by mutableStateOf("")

    // 使用 MutableStateFlow 和 map 来替代 MutableStateMap
    private val _isFollowingMap = MutableStateFlow<Map<String, Boolean>>(emptyMap())
    val isFollowingMap: StateFlow<Map<String, Boolean>> get() = _isFollowingMap

    fun setIsFollowing(userId: String, isFollowing: Boolean) {
        viewModelScope.launch {
            _isFollowingMap.value = _isFollowingMap.value.toMutableMap().apply { this[userId] = isFollowing }
        }
    }

    fun getIsFollowing(userId: String): Boolean {
        return _isFollowingMap.value[userId] ?: false
    }
    // 当前登录的用户信息
    var currentUserInfo by mutableStateOf<UserInfo?>(null)

    private var refreshJob: Job? = null


    // 图片选择回调
    var selectImage: () -> Unit by mutableStateOf({})

    private val activePlayers = mutableMapOf<String, ExoPlayer>()

    private val _currentPlayingIndex = mutableStateOf(-1)
    val currentPlayingIndex: Int get() = _currentPlayingIndex.value

    fun setCurrentPlayingIndex(index: Int) {
        _currentPlayingIndex.value = index
    }

    fun registerPlayer(postId: String, player: ExoPlayer) {
        activePlayers[postId] = player
    }

    fun unregisterPlayer(postId: String) {
        activePlayers[postId]?.release()
        activePlayers.remove(postId)
    }

    fun setPlayState(postId: String, play: Boolean) {
        activePlayers[postId]?.playWhenReady = play
    }
    init {
        loadRecommendations()
        postId.value?.let { loadComments(it) }
    }


    suspend fun judgeIsFollowed(followingId: String, followerId: String?): Boolean {
        return try {
            val response = MyRetrofitDatasource.judgeIsFollowed(followingId, followerId)
            Log.d("HomeViewModel", "judgeIsFollowed: followingId=$followingId, followerId=$followerId, response=${response.data}")
            response.data == true
        } catch (e: Exception) {
            Log.e("HomeViewModel", "数据加载失败", e)
            false
        }
    }

    private fun loadRecommendations() {
        viewModelScope.launch {
            try {
                val userId = SessionManager.currentUser?.id ?: return@launch
                // 并行请求用户和帖子数据
                val usersDeferred = async { MyRetrofitDatasource.getRecommendUserList(userId) }
                val postsDeferred = async { MyRetrofitDatasource.getRecommendPostList(userId) }

                userDatum.value = usersDeferred.await().data ?: emptyList()
                postDatum.value = postsDeferred.await().data ?: emptyList()
                currentUserInfo = SessionManager.currentUser
            } catch (e: Exception) {
                Log.e("HomeViewModel", "数据加载失败", e)
            }
        }
    }

     fun sendFollowRequest(followingId: String, followerId: String) {
        viewModelScope.launch {
            try {
                val response = MyRetrofitDatasource.judgeIsFollowed(followingId, followerId)
                if (response.data == false) {
                    val result = MyRetrofitDatasource.sendFollowRequest(followingId, followerId)
                    Log.d("HomeViewModel", "发送关注请求成功:${result}")
               }
            } catch (e: Exception) {
                Log.e("HomeViewModel", "数据加载失败", e)
            }
        }
    }

     fun sendUnFollowRequest(followingId: String, followerId: String) {
        viewModelScope.launch {
            try {
                val response = MyRetrofitDatasource.judgeIsFollowed(followingId, followerId)
                if (response.data == false) {
                    val result = MyRetrofitDatasource.sendUnFollowRequest(followingId, followerId)
                    Log.d("HomeViewModel", "发送取消关注请求成功:${result.data}")
                }
            } catch (e: Exception) {
                Log.e("HomeViewModel", "数据加载失败", e)
            }
        }
    }


    // 改为使用CommentDTO列表
    private val _comments = MutableStateFlow<List<CommentDTO>>(emptyList())
    val comments = _comments.asStateFlow()



    fun sendComment(comment: CommentDTO) {
        viewModelScope.launch {
            try {
                // 1. 先本地添加（临时显示）
                _comments.update { list ->
                    listOf(comment) + list // 按时间降序，新评论在前
                }

                // 2. 实际发送到服务器
                val response = MyRetrofitDatasource.createNewComment(comment)

                // 3. 成功后重新加载最新数据确保一致性
                if (response.data != null) {
                    postId.value?.let { loadComments(it) }
                }
            } catch (e: Exception) {
                // 回滚本地添加
                _comments.update { it.filterNot { c -> c.id == comment.id } }
            }
        }
    }

     fun loadComments(postId: String) {
        viewModelScope.launch {
            Log.d("HomeViewModel", "loadComments: postId=$postId")
            val response = MyRetrofitDatasource.getCommentListByPostId(postId)
            _comments.value = response.data?.sortedByDescending { it.timestamp } ?: emptyList()
            Log.d("HomeViewModel", "loadComments: ${comments.value}")
        }
    }



}